package com.benyi.util; 

import java.lang.reflect.Field;
import java.lang.reflect.Type; 
import java.util.ArrayList;
import java.util.HashMap;  
import org.springframework.beans.BeanUtils;
 
/*
	BeanUtils.copyProperties(Object source, Object target) 
	BeanUtils.copyProperties(Object source, Object target, Class<?> editable) 
	BeanUtils.copyProperties(Object source, Object target, String... ignoreProperties) 
*/

public class CopyTool { 
	private static final String []BASE= {"boolean","char","int","float","double","short","long","java.lang.String",
			"java.lang.Boolean","java.lang.Char","java.lang.Integer","java.lang.Float","java.lang.Double",
			"java.lang.Short","java.lang.Long","java.math.BigDecimal","java.util.Date" };
	
	private static HashMap<String,String[]> buffer = new HashMap<String,String[]>();
	
	public static boolean isBase(String n) {
		for(int i=0;i<BASE.length;i++) {
			if(BASE[i].equalsIgnoreCase(n)) {
				return true;
			}
		}
		return false;
	}
	
	public static String[] getComplexFields(Class c) {
		if(c == null) {
			String []r = {};
			return r;
		}
		
		String key = c.getName();
		String []ingores=buffer.get(key);
		if( ingores != null ) {
			return ingores;
		}
		 
		Type t;
		String tn;
		ArrayList<String> rs = new ArrayList<String>();
		Field[] fl = c.getDeclaredFields();
		for(int i=0;i<fl.length;i++) { 
			t = fl[i].getAnnotatedType().getType();
			tn = t.getTypeName(); 
			if(isBase(tn)) {
				continue;
			}
			rs.add(fl[i].getName()); 
		}
		ingores = new String[rs.size()];
		for(int i=0;i<ingores.length;i++) {
			ingores[i] = rs.get(i);
		}
		buffer.put(key, ingores); //buffer for next use
		return ingores;
	}
	
	
	public static Object copy(Object o) {
		if(o==null) return null;
		Object n = null;
		try {
			n = o.getClass().newInstance();
		}catch(Exception e) {
			e.printStackTrace();
		}
		String []ingores = getComplexFields(o.getClass());
		
		if(n == null) return null;
		BeanUtils.copyProperties(o, n,ingores); 
		return n;
	} 
 
}
